const jwt = require('jsonwebtoken');

const { JWT_SECRET } = require('../config/config.default');

const auth = async (ctx, next) => {
    const { authorization = "" } = ctx.request.header;
    const token = authorization.replace('Bearer ', '');
    try {
        const user = jwt.verify(token, JWT_SECRET);
        ctx.state.user = user;
    } catch (err) {
        switch (err.name) {
            case 'TokenExpiredError':
                console.log('token已过期', err);
                return ctx.body = { message: 'token已过期,请重新登陆' };
            case 'JsonWebTokenError':
                console.log('无效的token', err);
                return ctx.body = { message: 'token无效' };
        }
    }
    await next();
}

module.exports = { auth };
